<template>
  <div class="header-container">
    <div class="l-content">
      <el-button @click="handleMenu" size="mini" >
        <i :class="`el-icon-s-${status}`" ></i>
      </el-button>
    </div>
    <div class="r-content">
      <el-dropdown @command="handleClick">
            <span class="el-dropdown-link">
            <span style="font-size:14px;color:aqua;margin-right: 1em;padding-bottom: 0">{{user.name}}</span><img  class="user" src="../assets/images/user.png" alt="">
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
              <el-dropdown-item command="cancel">退出</el-dropdown-item>
            </el-dropdown-menu>
      </el-dropdown>
      <el-dialog  title="修改密码"
                  :visible.sync="dialogChangeVisible"
                  width="23%"
                  :destroy-on-close="true"
                  :before-close="handleFormClose"
      >
        <el-form ref="formPassword" :rules="rulesPassword"  :model="formPassword">
          <el-form-item label="新密码" prop="password">
            <el-input placeholder="请输入新密码" v-model="formPassword.password">
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="password_confirmation">
            <el-input placeholder="请确认新密码" v-model="formPassword.password_confirmation">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
              <el-button @click="cancelModify">取 消</el-button>
              <el-button type="primary" @click="submitModify">确 定</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import Cookies from "js-cookie"
import {logout,changePwd} from "@/api/user";

export default {
  name: "CommonHeader",
  data(){
    return {
      dialogChangeVisible:false,
      user:{
        name:Cookies.get('name')
      },
      status:'fold',
      formPassword:{
        password:'',
        password_confirmation:''
      },
      rulesPassword:{
        password: [
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur'
          },
          {
            min:8,
            max:16,
            message: '长度在8到16个字符之间',
            trigger: 'blur'
          },
          {
            pattern:"^(?!.*[！·（）{}【】“”：；，》￥、。‘’——\\s-……%\\n])(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/])[^\\u4e00-\\u9fa5]{8,16}$",
            message: '必须包含数字、小写字母、大写字母',
            trigger: 'blur'
          }
        ],
        password_confirmation: [
          {
            required: true,
            message: '请确认新密码',
            trigger: 'blur'
          },
          {
            min:8,
            max:16,
            message: '长度在8到16个字符之间',
            trigger: 'blur'
          },
          {
            pattern:"^(?!.*[！·（）{}【】“”：；，》￥、。‘’——\\s-……%\\n])(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/])[^\\u4e00-\\u9fa5]{8,16}$",
            message: '必须包含数字、小写字母、大写字母',
            trigger: 'blur'
          }
        ]
      },
    }
  },
  methods:{
    // 删除url中某个参数,并跳转
  funcUrlDel(name){
  var loca = window.location;
  var baseUrl = loca.origin + loca.pathname + "?";
  var query = loca.search.substr(1);
  if (query.indexOf(name)>-1) {
    var obj = {}
    var arr = query.split("&");
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split("=");
      obj[arr[i][0]] = arr[i][1];
    }
    delete obj[name];
    var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
    return url
  }
},
handleMenu(){
      this.$store.commit('collapseMenu')
      if(this.status==='fold'){
        this.status = 'unfold'
      }else{
        this.status = 'fold'
      }
    },
    handleClick(command){
      if(command==='cancel'){
        console.log('登出')
        let base = this.funcUrlDel("appToken")
        console.log('base',base)
        //清除cookie中的menu
        Cookies.remove('menu')
        this.$confirm('此操作将注销登录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          logout().then((res)=>{
            console.log(res)
            Cookies.remove('name')
            Cookies.remove('code')
            Cookies.remove('postName')
            Cookies.remove('roleName')
            this.$router.push({ path: '/login'})
            this.$store.commit('clearMenu')
            this.$store.commit('delUserInfo')
            Cookies.set('appToken','logout')
            this.$message({
              type:'success',
              message:'注销成功'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }else{
          this.dialogChangeVisible = true
      }
    },
    handleFormClose(){
      this.$refs.formPassword.resetFields()
      this.formPassword.password=''
      this.formPassword.password_confirmation=''
      this.dialogChangeVisible = false
    },
    cancelModify(){
      this.handleFormClose()
    },
    submitModify(){
      this.$refs.formPassword.validate((valid) => {
        if (valid) {
          if(this.formPassword.password===this.formPassword.password_confirmation){
            changePwd(this.formPassword).then(res=>{
              if(res.code===200){
                this.dialogChangeVisible=false
                this.$message.success(res.msg)
              }else{
                this.dialogChangeVisible=false
                this.$message.error(res.msg)
              }
            })
          }else{
            this.$message.error('请确认两次密码输入是否一致！')
          }
        }else{
          console.log('修改密码失败!!')
          this.$message.error('请输入所有字段！');
          return false
        }
      })
    }
  },
  computed:{
    ...mapState({
        tags:state => state.tab.tabsList
             })
  },
  mounted() {

  }
}
</script>

<style lang="less" scoped>
.header-container{
  padding: 0 20px;
  background-color: #146CB4;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .text{
    color: #fff;
    font-size: 14px;
    margin-left: 10px;
  }
  .r-content{
    .user{
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
  }
  .l-content{
    display: flex;
    align-items: center;
    /deep/.el-breadcrumb__item{
      .el-breadcrumb__inner{
        font-weight: normal;
        &.is-link{
          color: #666;
        }
      }
      &:last-child{
        .el-breadcrumb__inner{
          color:#fff
        }
      }
    }
  }
}
</style>
